package com.gl.goods.net.converter;

/**
 * @ClassName GsonResponseBodyConverter
 * @Author name
 * @Date 1/26/21
 * Description
 */

import android.content.Intent;

import com.gl.goods.base.BaseBean;
import com.gl.goods.base.MyApplication;
import com.gl.goods.ui.login.activity.LoginActivity;
import com.gl.library.tool.RxSPTool;
import com.gl.library.tool.RxTool;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import java.io.IOException;
import java.io.StringReader;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by AItsuki on 2016/12/16.
 */
final class ResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private static final int FAILURE = 0;       // 失败 提示失败msg
    private static final int SUCCESS = 1;       // 成功
    private static final int TOKEN_EXPIRE = -1;  // token过期
    private static final int SERVER_EXCEPTION = 3;  // 服务器异常

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    ResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String json = value.string();
        try {
            verify(json);
            return adapter.read(gson.newJsonReader(new StringReader(json)));
        } finally {
            value.close();
        }
    }

    private void verify(String json) {
        BaseBean result = gson.fromJson(json, BaseBean.class);
        if (result.getCode() != SUCCESS) {
            switch (result.getCode()) {
                case FAILURE:
                case SERVER_EXCEPTION:
//                    throw new ApiException(result.msg);
                case TOKEN_EXPIRE:
                    MyApplication.getInstance().logout();
                    RxSPTool.putInt(RxTool.getContext(), "memberId", 0);
                    RxSPTool.putString(RxTool.getContext(), "token", "");
                    Intent i = new Intent(RxTool.getContext(), LoginActivity.class);
                    RxTool.getContext().startActivity(i);
                default:
//                    throw new UndefinedStateException();
            }
        }
    }
}